package com.photoeditor.demo.model.image.emoji;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

import com.common.base.ComponentContext;

import java.util.ArrayList;

/**
 * 
 * 异步的Handler 用于加载Emoji
 * 不是单例
 */
public class StickerSyncHandler {

	private static final String TAG = StickerSyncHandler.class.getSimpleName();

	private Handler mHandler;

	private HandlerThread mThread;

	private Looper mLooper;

	private ArrayList<IEmojiLoadListener> mListeners;

	public static final int MSG_INIT_EMOJI_DATA = 0x100;

	public static final int MSG_REFRESH_EMOJI_DATA = 0x101;

	public StickerSyncHandler(){
		mListeners = new ArrayList<IEmojiLoadListener>();
		mThread = new HandlerThread(TAG, Thread.NORM_PRIORITY);
		mThread.start();
		mLooper = mThread.getLooper();
		initHandler(mLooper);
	}
	
	private void initHandler(Looper looper){
		mHandler = new Handler(mLooper){
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what){
				case MSG_INIT_EMOJI_DATA:
					LocalStickerData.getInstance();
					for(IEmojiLoadListener listener : mListeners){
						listener.onLoadEmojiFinish();
					}
					break;
				case MSG_REFRESH_EMOJI_DATA:
					LocalStickerData.getInstance().loadEmojiData(ComponentContext.getContext());
					for(IEmojiLoadListener listener : mListeners){
						listener.onLoadEmojiFinish();
					}
					break;
				default:
					break;
				}
			}
		};
	}

	public void startLoadEmojiApkDetailInfo(){
		mHandler.sendEmptyMessage(MSG_INIT_EMOJI_DATA);
	}

	public void refreshEmojiApkDetailInfo(){
		mHandler.sendEmptyMessage(MSG_REFRESH_EMOJI_DATA);
	}

	public void addListener(IEmojiLoadListener listener){
		mListeners.add(listener);
	}

	/**
	 * 回收 在Activity onDestory的时候回收
	 */
	public void destory(){
		try{
			mListeners.clear();
			mLooper.quit();
			mHandler.removeCallbacksAndMessages(null);
		} catch (Throwable e){

		}
	}
}
